<?php
/**
 * @author xp
 */
$list = file_get_contents('./encoded.txt');
$items = explode("\n", $list);

$handlers = [
    'vmess' => function ($uri) {
        if (strpos($uri, '?') !== false) {
            list($body, $args) = explode('?', $uri);
        } else {
            $body = $uri;
            $args = '';
        }
        $body = base64_decode($body);
        list($auth, $loc) = explode('@', $body);
        list($method, $uuid) = explode(':', $auth);
        if ($loc[0] == '[') {
            // ipv6
            $pos = strrpos(':', $loc);
            $host = substr($loc, 0, $pos);
            $port = intval(substr($loc, $pos + 1));
        } else {
            // ipv4 or domain
            list($host, $port) = explode(':', $loc);
        }
        return [
            'vmess',
            $body,
            $loc, // $host, $port,
            $method, $uuid,
            '?', $args
        ];
    },
    'ss' => function ($uri) {
        if (strpos($uri, '/') !== false) {
            list($body, $args) = explode('/', $uri);
        } else {
            $body = $uri;
            $args = '';
        }
        $body = base64_decode($body);
        list($auth, $loc) = explode('@', $body);
        list($method, $pass) = explode(':', $auth);
        return [
            'ss',
            $body,
            $loc, // $host, $port,
            $method, $pass,
            '/', $args
        ];
    },
];

$plains = [];
foreach ($items as $rest) {
    $rest = trim($rest);
    if (empty($rest)) {
        $plains[] = '';
        continue;
    }

    if ($rest[0] == '#') {
        $plains[] = $rest;
        continue;
    }

    if (strpos($rest, '://') === false) continue;
    list($protocol, $rest) = explode('://', $rest);
    if (!array_key_exists($protocol, $handlers)) {
        echo 'unknown: ' . $protocol . "\n";
        continue;
    }
    $plains[] = $handlers[$protocol]($rest);
}

foreach ($plains as $line) {
    if (is_string($line)) {
        echo $line . "\n";
    } else {
        assert(is_array($line));
        echo $line[0] . '://' . $line[1] . $line[5] . $line[6] . "\n";
    }
}
